<template>
  <div>
    <common-search ref="SearchData" titleName="管理员名字"></common-search>
    <el-main>
      <el-button type="danger" round @click="delByIds">删除已选中</el-button>
      <el-button type="success" round @click="dialogFormVisible=true">添加新管理员</el-button>
      <el-table :data="tableData.records" @selection-change="addIds">
        <!-- 勾选 -->
        <el-table-column type="selection">
        </el-table-column>
        <el-table-column label="头像" width="240">
          <template slot-scope="scope">
            <el-avatar icon="el-icon-user-solid" shape="square" :src="scope.row.profilePhoto" :key="scope.row.profilePhoto"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="120">
        </el-table-column>
        <el-table-column label="是否超级管理员" :formatter="testRoot" width="120">
        </el-table-column>
        <el-table-column label="是否可用" :formatter="testUse" width="120">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 删除 -->
            <el-button type="danger" 
                      icon="el-icon-delete" 
                      circle 
                      :disabled="canDo(scope.row)"
                      @click.native.prevent="delById(scope.row)"></el-button>
            <!-- 修改 -->
            <el-button type="primary" 
                      icon="el-icon-edit" 
                      circle
                      @click.native.prevent="updateById(scope.row)"></el-button>
            <!-- 修改新增表单转移至el-main下方 -->
            <!-- <el-dialog title="管理员信息" :visible.sync="dialogFormVisible" close-on-press-escape :before-close="clearUpdateData">
              <el-form :model="manager">
                <el-form-item label="管理员名称" :label-width="formLabelWidth">
                  <el-input v-model="manager.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="管理员名称密码" :label-width="formLabelWidth">
                  <el-input v-model="manager.password" autocomplete="off" show-password></el-input>
                </el-form-item>
                <el-form-item label="管理员头像" :label-width="formLabelWidth">      
                  <el-upload
                    name="photo"
                    class="avatar-uploader"
                    action="http://localhost/graduateprogram/manager/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="manager.profilePhoto" :src="manager.profilePhoto" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item label="是否可用" :label-width="formLabelWidth">
                  <el-switch
                    v-model="manager.canUse"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                  </el-switch>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="clearUpdateData">取 消</el-button>
                <el-button type="primary" @click="updateManagerByIdArAddNew" :loading="uploading">确 定</el-button>
              </div>
            </el-dialog> -->
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <!-- 修改新增表单新位置 -->
    <el-dialog title="管理员信息" :visible.sync="dialogFormVisible" close-on-press-escape :before-close="clearUpdateData">
      <el-form :model="manager">
        <el-form-item label="管理员名称" :label-width="formLabelWidth">
          <el-input v-model="manager.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="管理员名称密码" :label-width="formLabelWidth">
          <el-input v-model="manager.password" autocomplete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="管理员头像" :label-width="formLabelWidth">      
          <el-upload
            name="photo"
            class="avatar-uploader"
            action="http://localhost/graduateprogram/manager/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="manager.profilePhoto" :src="manager.profilePhoto" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否可用" :label-width="formLabelWidth" v-if="!canDo(manager)">
          <el-switch
            v-model="manager.canUse"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearUpdateData">取 消</el-button>
        <el-button type="primary" @click="updateManagerByIdArAddNew" :loading="uploading">确 定</el-button>
      </div>
    </el-dialog>
    <common-footer :pageData="tableData" ref="footData"></common-footer>
  </div>
</template>
<script>
import CommonSearch from '@/components/CommonSearch.vue';
import CommonFooter from '@/components/CommonFooter.vue';
import axios from 'axios';
    export default {
      name:'RootPerson',
      data() {
        return{
          tableData:{},
          searchD:'',
          ids:[],
          dialogFormVisible:false,
          manager: {
            id:'',
            name: '',
            password: '',
            profilePhoto: '',
            root:false,
            canUse: true,
          },
          formLabelWidth: '120px',
          uploading: false,
        }
      },
      components:{CommonSearch,CommonFooter},
      props:["page","pageSize"],//page:当前页码，pageSize:每页个数
      mounted() {
        this.$refs.SearchData.$on('searchData',this.getRootByName);//接受子组件搜索栏目的数据
        this.$refs.footData.$on('pageSize',this.getPageSize);//接收子组件分页栏的每页显示条目数
        this.$refs.footData.$on('currentPage',this.getCurrentPage);//接收子组件分页栏的数据
        axios.get(`/manager/getPage?page=${this.page}&pageSize=${this.pageSize}`).then(
          response=>{
              this.tableData=response.data.data
            },
          error=>{
            console.log("请求失败。原因是",error.message);
          }
        )
      },
      methods:{
        testUse(row){//处理布尔类型数据显示
            if(row.canUse===true){
              return '是';
            }else{
              return '否';
            }
        },
        testRoot(row){//处理布尔类型数据显示
          if(row.root===true){
              return '是';
            }else{
              return '否';
            }
        },
        getRootByName(name){//作为搜索子组件传的数据的回调函数，调用分页模糊查询
          this.searchD=name;
          if(this.tableData.current===1){
            this.updataPageData();
          }else{
            this.tableData.current=1;
          }
        },
        getPageSize(pagesize){//为data数据this.tableData.size赋值每页个数
          this.tableData.size=pagesize;
        },
        getCurrentPage(currentpage){//为data数据this.tableData.current赋值当前页数
          this.tableData.current=currentpage;
        },
        updataPageData(){//因翻页、改变每页数据、有新的搜索数据、删除了某数据之后进行的刷新数据的作用
          axios.get(`/manager/getPage?page=${this.tableData.current}&pageSize=${this.tableData.size}&name=${this.searchD}`).then(
            response=>{
                this.tableData=response.data.data;
                this.manager={
                  id:'',
                  name: '',
                  password: '',
                  profilePhoto: '',
                  root:false,
                  canUse: true,
                }
            },
            error=>{
                console.log("请求失败。原因是",error.message);
            }
          );
        },
        delById:async function(roo){//根据id删除某数据
          if(confirm("确定删除管理员“"+roo.name+"”吗")){
            await new Promise((resolve)=>{
              axios.get(`/manager/delById?id=${roo.id}`).then(resolve());   
            })
            await new Promise((resolve)=>{
              this.updataPageData().then(resolve());
            })
            this.$forceUpdate();//迫使Vue实例重新渲染
          }
        },
        delByIds:async function(){//根据id数组批量删除数据
          if(confirm("确定删除所有已选中的管理员吗？")&&this.ids.length!==0){
            await new Promise((resolve)=>{
              let params=new URLSearchParams();
              params.append('ids',this.ids);
              axios(
                {
                  method:'get',
                  url:'/manager/delByIds',
                  params
                }
              ).then(
                response=>{
                  response;
                  resolve();
                }
              );
            })
            this.tableData.current=1;
            await new Promise((resolve)=>{
              this.updataPageData().then(resolve());
            })
            this.$forceUpdate();//迫使Vue实例重新渲染
          }
        },
        addIds(val){//多选删除时每次勾选都要更新一次勾选的数据
          var momentIds=[];
          val.forEach((data) => {
            momentIds.push(data.id)
          });
          this.ids=momentIds;
        },

        handleAvatarSuccess(res) {//图片上传成功后返回地址
          this.manager.profilePhoto=res.data;
          this.uploading=false;
        },
        beforeAvatarUpload(file) {//图片上传之前进行校验
          this.uploading=true;
          const isJPG = file.type === 'image/jpeg';
          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
            this.uploading=false;
          }
          if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            this.uploading=false;
          }
          return isJPG && isLt2M;
        },
        updateById(val){//进入修改页面
          this.dialogFormVisible = true;//开启信息页面
          this.manager.name=val.name;
          this.manager.password=val.password;
          this.manager.profilePhoto=val.profilePhoto;
          this.manager.canUse=val.canUse;
          this.manager.root=val.root;
          this.manager.id=val.id;
        },
        updateManagerByIdArAddNew(){//发请求进行修改或者新添
          this.dialogFormVisible = false;
          if(this.manager.id===''){//没有id则为新增
            axios(
              {
                method:'post',
                url:'/manager/addManager',
                data:this.manager
              }
            ).then(
              response=>{
                if(response.data.data===true){
                  alert('添加新管理员成功');
                  /*如果总页数×每页显示条数大于总记录数的话，则当前页的=总页数
                    反之当前页=总页数+1*/
                  if(this.tableData.size*this.tableData.pages>this.tableData.total){
                    /*如果当前页不在最后一页的话，只是当前页=最后一页，利用监控属性执行刷新
                    如果当前页在最后一页的话手动调用刷新*/
                    if(this.tableData.current<this.tableData.pages){
                      this.tableData.current=this.tableData.pages;
                    }else{
                      this.updataPageData();
                    }
                  }else{
                    if(this.tableData.current>this.tableData.pages){
                          this.updataPageData();
                    }else{
                        this.tableData.current=this.tableData.pages+1;
                    }
                  }
                }else{
                  alert('添加失败，请检查是否和其他管理员重名');
                  this.manager={
                    id:'',
                    name: '',
                    password: '',
                    profilePhoto: '',
                    root:false,
                    canUse: true,
                  }
                }
              }
            )
          }else{//有id则为修改
            axios(
                {
                  method:'post',
                  url:'/manager/updateManager',
                  data:this.manager,
                }
            ).then(
              response=>{
                if(response.data.data===true){
                  alert('修改管理员成功');
                  this.updataPageData();
                }else{
                  alert('修改失败，请检查是否和其他管理员重名');
                  this.manager={
                    id:'',
                    name: '',
                    password: '',
                    profilePhoto: '',
                    root:false,
                    canUse: true,
                  }
                }
              }
            );
          }       
        },
        clearUpdateData(){//关闭对话框时清空表单数据
          this.dialogFormVisible = false;
          this.manager={
            id:'',
            name: '',
            password: '',
            profilePhoto: '',
            canUse: true,
          };
        },
        canDo(val){//判断是否是自己，不能自己删除/禁用自己
          return JSON.parse(localStorage.getItem('managerData')).id===val.id;
        }
      },
      watch:{
        'tableData.size':{
            handler(newValue,oldValue){
              if(oldValue!==undefined){
                this.updataPageData();
              }
              
            }
        },
        'tableData.current':{
            handler(newValue,oldValue){
              if(oldValue!==undefined){
                this.updataPageData();
              }
            }
        }
      }
    }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>